'''
Created on 2011-1-16
This function is used to to generate the require command to start the openttd
It will read the xxx-xxxx-xx-xx.....command-out.log, find the last new map and it's seed.
It will generate the command likt openttd -G seed -D -R filename

<IMP> Because I compile the game without lzo2 in DAS3, So I remove it in Visual studio 2008
@author: Q
'''

import os,string, testSingleExpReplay

from Configuration import Configuration

cf = Configuration()

def getSeed(filename):
    file = open(filename);
    lines = file.readlines();
    seed = ""
    for line in lines:
        if(line.find("new_map:")>=0):
            tup = string.split(line)
            seed = tup[1]
    print "Hex", seed
    ret = int(seed, 16)
    print "Dec", ret
    return ret

def getSaveMapNameBeforeAutosave(filename):
    file = open(filename);
    lines = file.readlines();
    savfile = ""
    for line in lines:
        if(line.find("save:")>=0):
            tup = string.split(line)
            if tup[3].find("autosave")>=0:
                continue
            savfile = tup[3]
    return savfile

def modifyReplayNewAIToNewCompany():
    return True;

def generateOpenttdCommand(filename):
    cmd = "openttd -G %d"%getSeed(filename) + " -D -R " + filename
    print cmd
    return cmd

def getOpenTTDReplayCommand(expId, expName, factor, nodeName):
    path = cf.getAutoSavePath(expName)
    prefix = "%d_"%expId + expName + "_%d_"%factor + nodeName + "_" 
    commandLogName = prefix + "commands-out.log"
    saveFileName = getSaveMapNameBeforeAutosave(os.path.join(path, commandLogName))
    saveFileName = prefix + saveFileName
    #cd /var/tmp/sshen/run; nohup ./openttd -d 1 -x -D&
    precmd = "cd /var/tmp/sshen/run; nohup "
    cmd = precmd + "./replay -D -g " + os.path.join(path, saveFileName) + " -R " + os.path.join(path, commandLogName)
    return cmd
#    return (saveFileName, commandLogName)
if __name__ == "__main__":
    expId = 1000 
    expName = "replay-1a7"
    factor = 178
    cmd = getOpenTTDReplayCommand(683,"1a7", 178, "node332")
    print cmd
#    testSingleExpReplay.testSingle(expId, expName, 1, factor, "nullPath", "ft", cmd)
#    generateOpenttdCommand("D:\\tudworkspace\\683_1a7_178_node332_commands-out.log")
#    print getSaveMapNameBeforeAutosave("D:\\tudworkspace\\683_1a7_178_node332_commands-out.log")
    
